package com.cat.binaryTree;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/sort-list/
 * @create 2025/9/27 20:54
 * @since JDK17
 */

public class Solution76 {
    ListNode merge(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(-1), p = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                p = p.next = l1;
                l1 = l1.next;
            } else {
                p = p.next = l2;
                l2 = l2.next;
            }
        }
        if (l1 != null) {
            p.next = l1;
        } else {
            p.next = l2;
        }
        return dummy.next;
    }
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode fast = head.next, slow = head, h2;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        h2 = slow.next;
        slow.next = null;
        head = sortList(head);
        h2 = sortList(h2);
        return merge(head, h2);
    }
}
